package web.server.test_bed;

import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;

import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.nio.DefaultServerIOEventDispatch;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.entity.NFileEntity;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.nio.protocol.BufferingHttpServiceHandler;
import org.apache.http.nio.protocol.EventListener;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.ListeningIOReactor;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpProcessor;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerRegistry;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
import org.apache.http.util.EntityUtils;
import org.kth.dks.JDHT;
import org.kth.dks.dks_exceptions.DKSIdentifierAlreadyTaken;
import org.kth.dks.dks_exceptions.DKSRefNoResponse;
import org.kth.dks.dks_exceptions.DKSTooManyRestartJoins;

import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;

import business.application.TFCalculator;
import business.application.test_bed.DBServerStandAlone;
import business.application.test_bed.QuerierStandAlone;
import business.search_eng.Document;
import business.search_eng.Querier;
import business.search_eng.ResultList;

public class NHttpServerStandAlone {
	
	public static DBServerStandAlone engine;


	public static void main(String[] args) throws Exception {
        if (args.length < 2) {
            System.err.println("Please specify document root directory and numofdocs");
            System.exit(1);
        }
        HttpParams params = new BasicHttpParams();
        params
            .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
        
      //Set up the DHT Gateway node
        long ini = System.currentTimeMillis();
        engine = new DBServerStandAlone(Integer.parseInt(args[1]));
        long end = System.currentTimeMillis();
        long time = end-ini;
        System.out.println(time+" ms elapsed");

		/*try {
			// Start an instance listening on port 5550
			//myDHT = new HashMap<String, String>(5550, args[1]);
		} catch (DKSTooManyRestartJoins e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (DKSIdentifierAlreadyTaken e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (DKSRefNoResponse e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}*/

        BasicHttpProcessor httpproc = new BasicHttpProcessor();
        httpproc.addInterceptor(new ResponseDate());
        httpproc.addInterceptor(new ResponseServer());
        httpproc.addInterceptor(new ResponseContent());
        httpproc.addInterceptor(new ResponseConnControl());

        BufferingHttpServiceHandler handler = new BufferingHttpServiceHandler(
                httpproc,
                new DefaultHttpResponseFactory(),
                new DefaultConnectionReuseStrategy(),
                params);

        // Set up request handlers
        HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
        reqistry.register("*", new HttpFileHandler(args[0]));
        reqistry.register("/query*", new HttpQueryHandler(args[0]));
        reqistry.register("/document*", new HttpDocumentHandler());
        reqistry.register("/relevance*", new HttpRelevanceHandler());


        handler.setHandlerResolver(reqistry);

        // Provide an event logger
        handler.setEventListener(new EventLogger());

        IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(handler, params);
        ListeningIOReactor ioReactor = new DefaultListeningIOReactor(2, params);
        try {
            ioReactor.listen(new InetSocketAddress(8080));
            System.out.println("Listening on localhost:8080");
            ioReactor.execute(ioEventDispatch);
        } catch (InterruptedIOException ex) {
            System.err.println("Interrupted");
        } catch (IOException e) {
            System.err.println("I/O error: " + e.getMessage());
        }
        //engine.close() -- no need
        //myDHT.close();
        System.out.println("Shutdown");
    }

    static class HttpFileHandler implements HttpRequestHandler  {

        private final String docRoot;

        public HttpFileHandler(final String docRoot) {
            super();
            this.docRoot = docRoot;
        }

        public void handle(
                final HttpRequest request,
                final HttpResponse response,
                final HttpContext context) throws HttpException, IOException {

            String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
            if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
                throw new MethodNotSupportedException(method + " method not supported");
            }

            if (request instanceof HttpEntityEnclosingRequest) {
                HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
                byte[] entityContent = EntityUtils.toByteArray(entity);
                System.out.println("Incoming entity content (bytes): " + entityContent.length);
            }

            String target = request.getRequestLine().getUri();
            final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8"));
            if (!file.exists()) {

                response.setStatusCode(HttpStatus.SC_NOT_FOUND);
                NStringEntity entity = new NStringEntity(
                        "<html><body><h1>File" + file.getPath() +
                        " not found</h1></body></html>", "UTF-8");
                entity.setContentType("text/html; charset=UTF-8");
                response.setEntity(entity);
                System.out.println("File " + file.getPath() + " not found");

            } else if (!file.canRead() || file.isDirectory()) {
            	
            	final File index = new File(file,"index.html");
            	if (index.exists()) {
            		response.setStatusCode(HttpStatus.SC_OK);
                    NFileEntity body = new NFileEntity(index, "text/html");
                    response.setEntity(body);
                    System.out.println("Redirecting to Serving file " + file.getPath());
            	} else {
	                response.setStatusCode(HttpStatus.SC_FORBIDDEN);
	                NStringEntity entity = new NStringEntity(
	                        "<html><body><h1>Access denied</h1></body></html>",
	                        "UTF-8");
	                entity.setContentType("text/html; charset=UTF-8");
	                response.setEntity(entity);
	                System.out.println("Cannot read file " + file.getPath());
            	}
            	
            } else {

                response.setStatusCode(HttpStatus.SC_OK);
                NFileEntity body = new NFileEntity(file, "text/html");
                response.setEntity(body);
                System.out.println("Serving file " + file.getPath());

            }
        }

    }
    
    static class HttpDocumentHandler implements HttpRequestHandler  {
        
        //private final String docRoot;
    	/*private DBServerStandAlone someengine = engine;
        
        public HttpDocumentHandler(DBServerStandAlone engine) {
            super();
            this.someengine = engine;
        }*/
    	
        public HttpDocumentHandler() {
            super();
        }
        
        public void handle(
                final HttpRequest request, 
                final HttpResponse response,
                final HttpContext context) throws HttpException, IOException {

            String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
            if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
                throw new MethodNotSupportedException(method + " method not supported"); 
            }
            String target = request.getRequestLine().getUri();
            System.out.println(target);

            if (request instanceof HttpEntityEnclosingRequest) {
                HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
                byte[] entityContent = EntityUtils.toByteArray(entity);
                System.out.println("Incoming entity content (bytes): " + entityContent.length);
            }
            
            // Descartem "/document?"
            String paramChain= target.substring(10);
            
            //Resolve params
            
            HashMap<String, String> parameters = new HashMap<String, String>();

            String[] params = paramChain.split("&");
            for(int i=0;i<params.length;i++){
            	parameters.put(params[i].split("=")[0], params[i].split("=")[1]);
            }          
            
            Document aDocument = null;    	
			aDocument = (Document) engine.collection.get(parameters.get("d"));
                
            response.setStatusCode(HttpStatus.SC_OK);
            NStringEntity content = new NStringEntity(aDocument.htmlData());
            content.setContentType("text/html; charset=UTF-8");
            response.setEntity(content);
            System.out.println("Serving a document");
        }
        
    }
    static class HttpRelevanceHandler implements HttpRequestHandler  {
        
        //private final String docRoot;
    	/*private DBServerStandAlone someengine = engine;
        
        public HttpDocumentHandler(DBServerStandAlone engine) {
            super();
            this.someengine = engine;
        }*/
    	
        public HttpRelevanceHandler() {
            super();
        }
        
        public void handle(
                final HttpRequest request, 
                final HttpResponse response,
                final HttpContext context) throws HttpException, IOException {

            String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
            if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
                throw new MethodNotSupportedException(method + " method not supported"); 
            }
            String target = request.getRequestLine().getUri();
            System.out.println(target);

            if (request instanceof HttpEntityEnclosingRequest) {
                HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
                byte[] entityContent = EntityUtils.toByteArray(entity);
                System.out.println("Incoming entity content (bytes): " + entityContent.length);
            }
            
            // Descartem "/document?"
            String paramChain= target.substring(11);
            
            //Resolve params
            
            HashMap<String, String> parameters = new HashMap<String, String>();

            String[] params = paramChain.split("&");
            for(int i=0;i<params.length;i++){
            	parameters.put(params[i].split("=")[0], params[i].split("=")[1]);
            }          
           
            storeRelevanceInDatabase(parameters.get("q"),parameters.get("l"));
                
            response.setStatusCode(HttpStatus.SC_OK);
            NStringEntity content = new NStringEntity("NO ESPIK INGLISH!");//aDocument.htmlData());
            content.setContentType("text/html; charset=UTF-8");
            response.setEntity(content);
            System.out.println("Serving a document");
        }

		private void storeRelevanceInDatabase(String query, String list) {
			boolean debug=false;
			Statement insertStmt = null;
			String insert = null;
			try {
				Class.forName("com.mysql.jdbc.Driver").newInstance();
				Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/tfcmargon?" +
				"user=zasca&password=zasca2009");
				
		        //prepapre the insert
				insertStmt = (Statement) conn.createStatement();
				//foreach relevant document in String list
				String[] docs = list.split(";");
				int i=0;
				while(i<docs.length) {
					String[] docInfo = docs[i].split(",");
					String docId = docInfo[0];
					String rel = docInfo[1].equals("true")?"1":"0";
					//0 = docid, 1 relevance (string true/false)
					insert = "insert into trec_queryres(query, docid, relevance) value (" +
					"'"+query+"'," +
					""+docId+"," +
					"'"+rel+"')";
			
					if(debug)
						System.out.println("\nINSERT:\n"+insert);
					insertStmt.executeUpdate(insert);
					i++;
				}
				
			} catch (SQLException ex){
			    // handle any errors
				System.out.println("\nINSERT:\n"+insert);
			    System.out.println("SQLException: " + ex.getMessage());
			    System.out.println("SQLState: " + ex.getSQLState());
			    System.out.println("VendorError: " + ex.getErrorCode());
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
			        
    }
    
    static class HttpQueryHandler implements HttpRequestHandler  {
        
        private final String docRoot;
    	//private JDHT myDHT;
        
        public HttpQueryHandler(String docRoot) {
            super();
            this.docRoot=docRoot;
            //this.myDHT = myDHT;
        }
        
        public void handle(
                final HttpRequest request, 
                final HttpResponse response,
                final HttpContext context) throws HttpException, IOException {
        	context.setAttribute("total", "10");

            String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
            if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
                throw new MethodNotSupportedException(method + " method not supported"); 
            }
            String target = request.getRequestLine().getUri();
            System.out.println(target);

            if (request instanceof HttpEntityEnclosingRequest) {
                HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
                byte[] entityContent = EntityUtils.toByteArray(entity);
                System.out.println("Incoming entity content (bytes): " + entityContent.length);
            }
            
            // Descartem /query?
            String paramChain= target.substring(7);
            
            //Resolve params
            
            HashMap<String, String> parameters = new HashMap<String, String>();

            String[] params = paramChain.split("&");
            for(int i=0;i<params.length;i++){
            	parameters.put(params[i].split("=")[0], params[i].split("=")[1]);
            }
            
            if(!parameters.get("q").isEmpty()) {
            
	            QuerierStandAlone system = new QuerierStandAlone(engine);
	            long ini = System.currentTimeMillis();
	            ResultList result = system.query(parameters.get("q").replace("%20", " "));
	            long end = System.currentTimeMillis();
	            System.out.println("time elapsed in ms "+(end-ini));
	            
	            response.setStatusCode(HttpStatus.SC_OK);
	            NStringEntity content = new NStringEntity(result.JSONstringify());
	  
	            content.setContentType("text/html; charset=UTF-8");
	            response.setEntity(content);
	            System.out.println("Serving a string "+result.JSONstringify());
            } else {
            	response.setStatusCode(HttpStatus.SC_OK);
            	File root = new File(docRoot, URLDecoder.decode(target, "UTF-8"));
            	File index = new File(root, "index.html");
                NFileEntity body = new NFileEntity( index, "text/html");
                response.setEntity(body);
                System.out.println("Redirecting to Serving file " + index.getPath());
            }
        }

		private String generateResponseFile(String json) {
			String pt1 = "<html><head><title> HOME Buffaloe Test Page</title><style>@import url('style.css');</style><script src='json2.js' type='text/javascript'></script><script type='text/javascript'>";
			String pt2 = "</script></head><body bgcolor='white' text='green' onload=\"alert('kaka')\"><h1>Test Page </h1>Some text of the new distributed search engine Buffaloe<div id='results'></div></body></html>";
			StringBuilder sb = new StringBuilder();	
			sb.append(pt1);
			sb.append("var docs = eval('(' + "+json+" + ')');");
			sb.append("alert (docs)");
			sb.append(pt2);
			
			return sb.toString();
		}
        
    }

    static class EventLogger implements EventListener {

        public void connectionOpen(final NHttpConnection conn) {
            System.out.println("Connection open: " + conn);
        }

        public void connectionTimeout(final NHttpConnection conn) {
            System.out.println("Connection timed out: " + conn);
        }

        public void connectionClosed(final NHttpConnection conn) {
            System.out.println("Connection closed: " + conn);
        }

        public void fatalIOException(final IOException ex, final NHttpConnection conn) {
            System.err.println("I/O error: " + ex.getMessage());
        }

        public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) {
            System.err.println("HTTP error: " + ex.getMessage());
        }

    }

}
